from flask import Flask, render_template, request, jsonify
from werkzeug.utils import secure_filename
import os
import numpy as np
from features.hybrid_analysis import HybridAnalyzer
from models.evaluation.evaluator import ModelEvaluator

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'uploads/'
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024  # 16MB

# 初始化检测组件
static_analyzer = StaticAnalyzer()
dynamic_analyzer = DynamicAnalyzer()
hybrid_analyzer = HybridAnalyzer(static_analyzer, dynamic_analyzer)
model = joblib.load('models/saved/rf_model.joblib')

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/scan', methods=['POST'])
def scan_file():
    if 'file' not in request.files:
        return jsonify({'error': 'No file uploaded'}), 400
        
    file = request.files['file']
    if file.filename == '':
        return jsonify({'error': 'Empty filename'}), 400
        
    try:
        # 保存上传文件
        filename = secure_filename(file.filename)
        filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
        file.save(filepath)
        
        # 执行混合分析
        analysis_result = hybrid_analyzer.analyze(filepath)
        
        # 模型预测
        features = analysis_result['selected_features'].reshape(1, -1)
        probability = model.predict_proba(features)[0][1]
        is_malicious = probability > 0.5
        
        return jsonify({
            'filename': filename,
            'malicious': bool(is_malicious),
            'confidence': float(probability),
            'static_features': analysis_result['static'],
            'dynamic_features': analysis_result['dynamic']
        })
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500

if __name__ == '__main__':
    os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
    app.run(host='0.0.0.0', port=5000, debug=True) 